<template>
  <div class="page">
    <div class="menu-box">
      <el-upload action="#" :multiple="false" :http-request="requestUpload" :before-upload="beforeUpload"
        accept=".pdf,.PDF" :show-file-list="false">
        <el-button icon="el-icon-upload2" style="margin: 50px 0 20px 0; width: 200px;font-weight: 500;
font-size: 18px;
color: #1a66ff;">上传文件</el-button>
      </el-upload>
      <el-divider></el-divider>
      <div class="list">
        <div class="item" :class="{ 'item-active': activeIndex == index }" v-for="(item, index) in fileList"
          :key="index" @click="itemClick(index)">
          <img class="pdf-icon" src="../../assets/images/pdf.png" alt="">
          <div class="file-name">{{ item.fileName }}</div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="pdf-controller">
        <template v-if="fileItem.fileName">
          <span v-if="fileItem.fileName.length > 45"> {{ fileItem.fileName }}</span>
          <div v-else>{{ fileItem.fileName }}</div>
        </template>
      </div>
      <div v-loading="loading" :element-loading-text="`文件加载中... ${progress} %`" class="pdf-box" ref="leftContainer" @scroll="syncScroll">
        <pdf class="pdf-page" v-for="i in numPages" :key="i" :src="pdfUrl" :page="i" @page-loaded="onPageLoaded"></pdf>

      </div>
    </div>
    <div class="content">
      <div class="pdf-controller">
        <div>解析结果</div>
        <el-button icon="el-icon-download" style="color: #1a66ff;position: fixed;right: 10px;"
          @click="dowondMd(fileItem.fileName, fileItem.markdown)">下载</el-button>
      </div>
      <div class="md-box" ref="rightContainer" @scroll="syncScroll">
        <!-- <vue-markdown v-if="fileItem.markdown">{{ fileItem.markdown }}</vue-markdown> -->
        <markdown-it-vue :options="options" class="md-body" :content="fileItem.markdown" />
      </div>
    </div>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import VueMarkdown from 'vue-markdown';
import MarkdownItVue from "markdown-it-vue";
import "markdown-it-vue/dist/markdown-it-vue.css";

import { uploadFile, listFile } from "@/api/front/index"
export default {
  name: 'AIPdf',
  components: {
    pdf,
    VueMarkdown,
    MarkdownItVue
  },
  data() {
    return {
      isScrolling: false,
      loading: false,
      progress:0,
      htmlMD: "",
      activeIndex: -1,
      numPages: 0,
      pdfUrl: '',
      scale: 1.0,
      mdContent: '',
      pdfSrc: '',
      options: {
        markdownIt: {
          html: true
        }
      },
      fileItem: {
        fileName: '',
        markdown: ''
      },
      fileList: []
    }
  },
  created() {

    this.loadMyFile()
  },

  methods: {
    itemClick(index) {
      this.activeIndex = index
      this.fileItem = this.fileList[index]
      this.fileItem.markdown = this.fileItem.markdown.replaceAll('[](images', `[](http://10.2.15.99:8000/images/${this.fileItem.fileId}`)
      this.numPages = 0
      this.getNumPages(`http://10.2.15.99:8000${this.fileItem.layoutPdf}`)
      this.$forceUpdate()
    },
    // 获取PDF总页数
    getNumPages(url) {
      let that = this
      this.loading = true
      let loadingTask = pdf.createLoadingTask(url)
      console.log(loadingTask);
      this.downLond = false
      that.progress = 0
      loadingTask.onProgress = (progressData) => {
        that.downLond = true
        const { loaded, total } = progressData;
        that.progress = Math.round((loaded / total) * 100);
      };
      loadingTask.promise.then(pdf => {
        console.log('then', pdf);
        that.numPages = pdf.numPages
        that.pdfUrl = loadingTask
      }).catch(res => {
        console.log('catch', res);
      })
      setTimeout(() => {
        if (!that.downLond) {
          that.itemClick(that.activeIndex)
        }
      }, 1000);
    },

    loadMyFile() {
      listFile({
        orderByColumn: 'id',
        isAsc: 'desc'
      }).then(res => {
        this.fileList = res.rows
      })
    },
    zoomIn() {
      this.scale += 0.1
      console.log('scale:', this.scale);

    },
    zoomOut() {
      this.scale -= 0.1
      console.log('scale:', this.scale);
    },
    syncScroll(event) {
      const target = event.currentTarget;
      const otherContainer = target === this.$refs.leftContainer ? this.$refs.rightContainer : this.$refs.leftContainer;

      // 防止循环触发
      if (this.isScrolling) return;
      this.isScrolling = true;

      // 计算当前滚动百分比
      const scrollPercentage = target.scrollTop / (target.scrollHeight - target.clientHeight);

      // 应用百分比到另一个容器
      otherContainer.scrollTop = scrollPercentage * (otherContainer.scrollHeight - otherContainer.clientHeight);

      // 使用nextTick确保DOM更新完成后重置标志
      this.$nextTick(() => {
        this.isScrolling = false;
      });
    },
    requestUpload() {

    },
    beforeUpload(file) {
      let formData = new FormData()
      formData.append('file', file)
      formData.append('fileName', file.name)

      uploadFile(formData).then(res => {
        console.log('uploadFile', res);

        this.$message({
          message: '文件上传成功',
          type: 'success'
        });
        this.loadMyFile()
      })
      return false
    },
    dowondMd(fileName, content) {
      const blob = new Blob([content], {
        type: 'text/markdown'
      })
      // 根据 blob生成 url链接
      const objectURL = URL.createObjectURL(blob)

      // 创建一个 a 标签Tag
      const aTag = document.createElement('a')
      // 设置文件的下载地址
      aTag.href = objectURL
      // 设置保存后的文件名称
      aTag.download = `${fileName.split('.')[0]}.md`
      // 给 a 标签添加点击事件
      aTag.click()
      // 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
      // 当你结束使用某个 URL 对象之后，应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
      URL.revokeObjectURL(objectURL)
    },
    onPageLoaded(value) {
      if (value == this, this.numPages) {
        this.loading = false
      }
    }
  }

}
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: row;
  height: 100vh;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.menu-box {
  width: 300px;
  box-sizing: border-box;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #E8EFFD;
}

.list {
  display: flex;
  flex-direction: column;
  height: 60vh;
  overflow-y: scroll;
  width: 100%;
  box-sizing: border-box;
}

.list::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条 */
}

.item {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin: 10px;
  padding: 10px;
  border-radius: 5px;
  border-radius: 8px;
  color: #333333;
  font-weight: 500;
}

.item:hover {
  font-weight: bold;
}

.item-active {
  color: #215FE1;
  font-weight: bold;
  background-color: #cadafc;
  border-radius: 3px;
}

.buttom-image {
  width: 240px;
  height: 45px;
  position: fixed;
  bottom: 20px;
  left: 30px;
}

.pdf-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;

}

.content {
  width: calc(50vw - 150px);
  display: flex;
  flex-direction: column;
  height: 100%;
  box-sizing: border-box;
  overflow-y: hidden;
}

.pdf-controller {
  width: 100%;
  height: 60px !important;
  box-sizing: border-box;
  background: white;
  ;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  color: #333;
  z-index: 10;
  padding: 0;
  margin: 0;
  overflow: hidden;
  white-space: nowrap;
}

.pdf-controller span {
  display: inline-block;
  padding-left: 100%;
  animation: marquee 15s linear infinite;
  /* 调整动画时长和效果 */
}

/* 定义关键帧动画 */
@keyframes marquee {
  0% {
    transform: translateX(0);
  }

  100% {
    transform: translateX(-100%);
  }
}

.number-box {
  margin: 0 20px;
  border: solid 1px #d1d1d1;
  border-radius: 5rpx;
  padding: 5px 10px;
}

.pdf-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow-y: scroll;
  background: #F2F5FA;
  box-sizing: border-box;
  padding: 10px;
}

.pdf-box::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条 */
}

.pdf-page {
  margin-bottom: 10px;
  border-image: linear-gradient(0deg, #FF9001, #FF0C0E) 10 10;
}

.md-box {
  box-sizing: border-box;
  padding: 50px 30px;
  overflow-y: scroll;
  flex: 1;
  box-sizing: border-box;
}
</style>
<style>
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  overflow: hidden !important;
}
</style>